package com.rpoonolly.simplegame.mapio.jsoncoders;

import java.io.IOException;

import org.json.simple.JSONObject;

import com.rpoonolly.simplegame.core.aabb.AABBEntity;
import com.rpoonolly.simplegame.core.aabb.EntityGameMap;
import com.rpoonolly.simplegame.worldGrid.WorldGrid;
import com.rpoonolly.simplegame.worldGrid.WorldGridGameMap;

public class WorldGridGameMapJSONCoder extends JSONCoder<WorldGridGameMap> {
	private static WorldGridGameMapJSONCoder singletonInstance = null;
	private JSONCoder<EntityGameMap<AABBEntity>> entityMapCoder;
	private JSONCoder<WorldGrid> worldGridCoder;

	private WorldGridGameMapJSONCoder() {
		entityMapCoder = EntityMapJSONCoder.getInstance();
		worldGridCoder = WorldGridJSONCoder.getInstance();
	}

	@SuppressWarnings("unchecked")
	@Override
	public JSONObject encode(WorldGridGameMap obj) throws IOException {
		JSONObject jsonMap = new JSONObject();
		jsonMap.put("entityMap", entityMapCoder.encode(obj));
		jsonMap.put("grid", worldGridCoder.encode(obj.getGrid()));
		
		return jsonMap;
	}

	@Override
	public WorldGridGameMap decode(JSONObject jsonMap) throws IOException{
		EntityGameMap<AABBEntity> entityMap = entityMapCoder.decode((JSONObject) jsonMap.get("entityMap"));
		WorldGrid grid = worldGridCoder.decode((JSONObject) jsonMap.get("grid"));
		
		return new WorldGridGameMap(entityMap.getEntities(), grid);
	}

	public static WorldGridGameMapJSONCoder getInstance() {
		if (singletonInstance == null)
			singletonInstance = new WorldGridGameMapJSONCoder();
		
		return singletonInstance;
	}
}
